<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from 'element-plus'
import { ElMessage } from "element-plus";
import { addIdentityAPI, editIdentityAPI } from "@/api/user.ts";
import { IdentityRules } from "@/view/Identity/utils/rules.ts";

const dialogTableVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const emit = defineEmits(["getIdentityList"])
const id = ref('')
const typeRef = ref(0)
const form = reactive({
  name: ''
})

// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 初始化
const init = (row: any, type: any) => {
  typeRef.value = type
  if (type === 0) {
    form.name = ''
  } else {
    id.value = row._id
    form.name = row.name
  }
  dialogTableVisible.value = true
}

// 取消
const handleCancel = () => {
  dialogTableVisible.value = false
  resetForm(ruleFormRef.value)
}

// 确认
const handleCommit = () => {
  ruleFormRef.value?.validate(async valid => {
    if (valid) {
      const res: any = await addIdentityAPI(form)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '添加成功'
        })
        emit('getIdentityList')
      }
      handleCancel()
    }
  })
}

// 修改
const handleChange = async () => {
  ruleFormRef.value?.validate(async valid => {
    if (valid) {
      const res: any = await editIdentityAPI(id.value, form)
      res.code === 0 ? ElMessage.success(res.message) : ElMessage.error(res.message)
      emit('getIdentityList')
      handleCancel()
    }
  })
}

defineExpose({
  init
})
</script>

<template>
  <div>
    <el-dialog width="30%" v-model="dialogTableVisible" :title="typeRef === 0 ? '添加身份' : '编辑身份'">
      <div class="row align_center">
        <el-form :model="form" ref="ruleFormRef" :rules="IdentityRules">
          <el-form-item prop="name" label="请输入名称：">
            <el-input v-model="form.name"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" v-if="typeRef === 0" @click="handleCommit">
          确认
        </el-button>
        <el-button type="primary" v-else @click="handleChange">
          修改
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>
